package article_api

import (
	"context"
	"encoding/json"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/olivere/elastic/v7"
	"giv-vue-blog/global"
	"giv-vue-blog/models"
	"giv-vue-blog/models/res"
	"giv-vue-blog/service/es_ser"
	"giv-vue-blog/utils/jwts"
)

// ArticleCollRemoveView 取消收藏接口
// @Summary 取消收藏文章
// @Description 用户取消收藏指定文章
// @Tags 文章管理
// @Accept json
// @Produce json
// @Param data body models.ESIDListRequest true "文章ID列表"
// @Security ApiKeyAuth
// @Success 200 {object} res.Response{}
// @Failure 400 {object} res.Response "参数错误"
// @Failure 401 {object} res.Response "未授权访问"
// @Failure 404 {object} res.Response "请求非法"
// @Failure 500 {object} res.Response "内部服务器错误"
// @Router /api/articles/collects [post]
func (ArticleApi) ArticleCollRemoveView(c *gin.Context) {
	var cr models.ESIDListRequest
	err := c.ShouldBindJSON(&cr)
	if err != nil {
		res.FailedWithCode(res.ArgumentError, c)
		return
	}
	_claims, _ := c.Get("claims")
	claims := _claims.(*jwts.CustomClaims)
	var collects []models.UserCollectModel
	var articleIDList []string
	global.DB.Find(&collects, "user_id=? and article_id in ?", claims.UserID, cr.IDList).
		Select("article_id").
		Scan(&articleIDList)
	if len(articleIDList) == 0 {
		res.FailedWithMsg("请求非法", c)
		return
	}
	var idList []interface{}
	for _, s := range articleIDList {
		idList = append(idList, s)
	}
	//更新文章数
	boolSearch := elastic.NewTermsQuery("_id", idList...)
	result, err := global.EsClient.
		Search(models.ArticleModel{}.Index()).
		Query(boolSearch).
		Highlight(elastic.NewHighlight().Field("title")). //文章高亮搜索
		//方法一 不显示content，它只会把这个内容在界面上渲染为空 因此采用另一种方法 在结构体中content字段后添加omit(list) 当在list时会把这个字段给去掉
		//FetchSourceContext(elastic.NewFetchSourceContext(true).Exclude("content")).
		Size(1000).
		Do(context.Background())
	if err != nil {
		res.FailedWithMsg(err.Error(), c)
		return
	}
	for _, hit := range result.Hits.Hits {
		var article models.ArticleModel
		err = json.Unmarshal(hit.Source, &article)
		if err != nil {
			global.Log.Error(err)
			continue
		}
		err = es_ser.ArticleUpdateCommon(hit.Id, map[string]any{
			"collects_count": article.CollectsCount - 1,
		})
		if err != nil {
			global.Log.Error(err)
			continue
		}
	}
	global.DB.Delete(&collects)
	res.OkWithMsg(fmt.Sprintf("成功从收藏列表中取消%d篇文章", len(articleIDList)), c)
}
